<template>
  <div>
    <el-card class="search-card">
      <BasicTableForm
        ref="formData"
        resetBtnName="重置"
        isBtnBarSingleRow
        :formColumns="formItemList"
        :dataSource="formData"
        :searchBtnRender="searchBtnRenderFn"
        @getFormData="getFormDataFn"
      />
    </el-card>
    <el-card class="table-card">
      <BasicTable
        showActionCol
        :actionColWidth="180"
        :showSelectCol="false"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :pageSizes="pageSizes"
        :tableHeight="480"
        :actionRender="renderTableActionFn"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      />
    </el-card>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { mapGetters } from 'vuex';
import BasicTableForm from '@/components/BasicForm';
import BasicTable from '@/components/BasicTable';
import { formItemList, getTableColumns } from '../constants/skuRejected';
import {
  isResponseSuccess,
  isResponseSuccessState,
  handleOpenNewPage
} from '@/utils/bizUtils';
export default {
  components: {
    BasicTableForm,
    BasicTable
  },
  data () {
    return {
      formData: {
        categoryPath: '',
        spuNo: '',
        productName: '',
        productType: '',
        operName: ''
      },
      formItemList: formItemList,
      tableInfo: {
        list: [],
        selection: [],
        columns: getTableColumns(this),
        loading: false
      },
      pagination: {
        nowPage: 1,
        totalNum: 0,
        pageShow: 10
      },
      pageSizes: [10, 20, 30, 40],
      apiObj: {
        getProductAddStateList: { // 获取表格数据
          url: '/sysback/product/addSku/stateInfo/getProductAddStateList',
          // url: '/sysback/prepare/list/getPreparingAddingList',
          type: 'post'
        },
        getAuditPageUrl: { // 审批记录跳OA接口
          url: '/sysback/oa/getAuditPageUrl',
          type: 'post'
        }
      }
    }
  },
  mounted () {
    this.handleSearch();
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  methods: {
    // 表单查询按钮
    searchBtnRenderFn () {
      return (
        <el-button
          type="primary"
          icon="el-icon-search"
          onClick={() => this.handleSearch()}
        >查询</el-button>
      )
    },
    // 获取表单数据
    getFormDataFn (formData) {
      this.formData = formData;
    },
    // 表格操作按钮
    renderTableActionFn (h, { row }) {
      const permissionBtns = [
        { label: '查看单据', methodFn: this.handleViewRecord },
        { label: '审批记录', methodFn: this.handleAuditRecord },
        { label: '删除', methodFn: this.handleToDelete, hasAuth: true },
      ];
      return (<div class="table-action">
        {permissionBtns.map(item => {
          const btn = <el-button
            type="text"
            onClick={() => item.methodFn(row)}
          >{item.label}</el-button>
          if (!item.hasAuth) { return btn; } // 没有权限的无需判断权限
          if (this.showBtn(item.label)) { return btn; }
        })}
      </div>);
    },
    // 删除
    handleToDelete (row) {
      this.$confirm('删除后将把该商品的所有完善信息删除，您确认吗？', '删除', {
        type: 'warning',
      }).then(() => {
        sessionStorage.setItem('buttonId', getBtnsId('删除'));
        this.deleteRecord(row.productUuid, row.spuNo);
      }).catch(() => {});
    },
    // 删除单据
    async deleteRecord (uuid, spuNo) {
      try {
        const url = `/sysback/product/addSku/stateInfo/deleteByProductuuid?uuid=${uuid}&spuNo=${spuNo}`
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, 'post');
        this.tableInfo.loading = false;
        if (isResponseSuccessState(res.retStatus)) {
          this.$message.success('删除成功');
          this.getTableDataFn();
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 查询表单
    handleSearch () {
      const curBtnId = getBtnsId('查询');
      sessionStorage.setItem('buttonId', curBtnId);
      this.pagination.nowPage = 1;
      this.getTableDataFn();
    },
    // 获取表格数据
    async getTableDataFn () {
      const data = {
        queryType: 4, // 查询类型 1 待完善 2 待提交 3 待审核 4 审核驳回
        ...this.formData,
        nowPage: this.pagination.nowPage,
        pageShow: this.pagination.pageShow,
      }
      const { url, type } = this.apiObj.getProductAddStateList;
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, type, data, false);
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          const { results, totalNum } = res.retData;
          this.tableInfo.list = results || [];
          this.pagination.totalNum = totalNum;
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 重置表单
    handleReset () {
      this.$refs.formData.handleResetForm();
    },
    // 页码切换
    handlePageChange (val) {
      this.pagination.nowPage = val;
      this.getTableDataFn();
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.pagination.pageShow = val;
      this.getTableDataFn();
    },
    // 查看单据
    handleViewRecord (row) {
      handleOpenNewPage(this, {
        name: 'viewSkuRecord',
        query: {
          recordNo: row.recordNo
        }
      });
    },
    // 审批记录
    async handleAuditRecord (row) {
      const { url, type } = this.apiObj.getAuditPageUrl;
      const apiUrl = `${url}?oaRequestId=${row.workflowRequestId}`;
      const res = await ApiRequest(apiUrl, type);
      window.open(res.retData);
    },
    // 链接子页面跳转
    handleLinkJump (row, pageRouterName, state) {
      const notJumpStateList = ['AUDITING', 'OK'];
      if (pageRouterName == 'skuPriceInfo' && (row.supplyPriceAddState == 'INIT' || row.supplyPriceAddState == 'FAIL')) {
        return this.$message.warning('请先完善供货信息');
      }
      // 路由name集合
      if (notJumpStateList.includes(state)) { return false; }
      /* handleOpenNewPage(this, {
        name: pageRouterName,
        query: {
          productUuid: row.productUuid,
          isPurchaseMultiUnit: row.isPurchaseMultiUnit
        }
      }); */
      this.$router.push({
        name: pageRouterName,
        query: {
          productUuid: row.productUuid,
          isPurchaseMultiUnit: row.isPurchaseMultiUnit
        }
      })
    },
    // 格式化link type
    formatLinkType (type) {
      const mappingList = {
        'INIT': 'primary', // 待完善
        'ADDING': 'primary', // 完善中
        'FAIL': 'danger', // 审核驳回
        'ADD_OK': 'success', // 已完善
        'AUDITING': 'info', // 审核中
        'OK': 'info' // 已完成
      }
      const linkType = mappingList[type] || 'info';
      return linkType;
    }
  }
}
</script>
